#include "runCommand.hpp"

#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>

namespace hms
{

std::string runCommand(const std::string& cmd) {
	std::array<char, 1024 * 64> buffer;
	std::string result;
	/* unique_ptr allows providing a destructor, which in this case is pclose */
	std::unique_ptr<FILE, decltype(&pclose)> pipe {
		popen(cmd.c_str(), "r"), pclose
	};
	if (!pipe) {
		throw std::runtime_error("popen() failed!");
	}
    std::size_t bytesread;
	while (( bytesread = fread(
		buffer.data(),
		sizeof(buffer.at(0)),
		sizeof(buffer),
		pipe.get()
		)) != 0
	){
		result += std::string{buffer.data(), bytesread};
	}
	return result;
}

} // namespace hms